<template>
    <div class="loginDiv">
        <div id="loginBack">
            <img id="backlogo" src="../../assets/images/login_bg.png"/>
        </div>
        <div class="loginForm">
            <el-tabs type="card" v-model="activeName">
                <el-tab-pane label="用户登录" name="userlogin">
                    <el-form ref="form" label-width="100px">
                        <el-form-item label="用户名">
                            <el-input v-model="loginUser.identify" placeholder="请输入注册手机/邮箱/账号"></el-input>
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input v-model="loginUser.password" placeholder="请输入密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="" style="margin-bottom: 0px">
                            <hua-kuai @verify='verify' @refresh='refresh'></hua-kuai>
                            记住我
                            <el-switch
                                    v-model="rememberme"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949">
                            </el-switch>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button style="width: 80%; display: block" @click="doLogin" type="primary" plain>登录
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="用户注册" name="userreg">
                    <el-form ref="form" label-width="100px">
                        <el-form-item label="用户名">
                            <el-input v-model="regUser.identify" placeholder="请输入注册手机/邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="">

                            <el-button @click="sendMsgToMobileOrEmail">发送验证码</el-button>
                            <!--
                            <img src="../../assets/images/vcode.png" title="看不清楚，换一张" style="cursor:pointer" @click="changeRandomCodeImg">
                            -->
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input v-model="regUser.password" placeholder="请输入密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码">
                            <el-input v-model="regUser.confirmpass" placeholder="请输入确认密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="验证码">
                            <el-input v-model="regUser.validateCode" placeholder="请输入验证码"></el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button style="width: 80%; display: block" type="success" @click="doReg" plain>注册
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script>

    import request from "@/util/request";
    import huakuai from '@/plugins/huakuai';
    /*
    //引入ElementUI的类库
    import Vue from 'vue';
    //引入所需的组件
    import {Tabs, TabPane, Form, FormItem, Button, Input, InputNumber, Switch, Message, MessageBox} from 'element-ui';
    //引入组件的样式表
    import 'element-ui/lib/theme-chalk/index.css';
    */
    //引入graceChecker组件
    import graceChecker from '@/util/graceChecker';
    //引入MyCookie组件
    import myCookie from '@/util/myCookie';

    //使用jsonwebtoken生成客户端的token
    let jwt = require("jsonwebtoken");
    /*
    //使用选中的组件
    Vue.use(Tabs);
    Vue.use(TabPane);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Button);
    Vue.use(Input);
    Vue.use(InputNumber);
    Vue.use(Switch);
    */
    export default {
        name: "MyLogin",
        data() {
            return {
                activeName: "userlogin",
                rememberme: true,
                token: jwt.sign({data: new Date().getMilliseconds()}, 'www.simoniu.com', {expiresIn: 6000 * 30}), //表示客户端的一个唯一的标识符
                loginUser: {
                    identify: '',
                    password: ''
                },
                regUser: {
                    identify: "", //输入的电子邮箱或者手机号码
                    email: "",
                    mobile: "",
                    password: "",
                    confirmpass: "",
                    validateCode: "",
                    flag: 1
                }
            }
        },
        mounted() {
            //初始化登录的账号。
            myCookie.getCookie(this.loginUser);
        },
        methods: {
            verify(result) {
                console.log(result) // result为true表示验证通过，false表示验证三次都失败了哦
                this.huakuaiFlag = result;
            },
            refresh() {
                console.log('用户点击了初始化')
            },

            changeTab(activeName) {
                //console.log('切换tab....,activeName='+activeName);
                this.activeName = activeName;
                //console.log("this.activeName:"+this.activeName);

            },

            //用户登录
            doLogin() {
                console.log('执行用户登录...');

                //先检查滑块验证的状态是不是true
                if (!this.huakuaiFlag) {
                    //Message.error('滑块验证失败！');
                    this.$message.error('滑块验证失败！');
                    return;
                }

                this.$store.dispatch("Login", this.loginUser).then(resp => {
                    if (resp.data.code === 200) {
                        //Message.success('登录成功！');
                        this.$message.success('登录成功！');
                        //判断一下用户是否需要记住我
                        if (this.rememberme) {
                            myCookie.setCookie(this.loginUser.identify, this.loginUser.password, 100);
                        } else {
                            myCookie.clearCookie(); //请求用户名和密码
                        }
                        //一旦登录成功之后，把登录成功的用户信息保存到本地缓存里面。
                        //而且把登录成功的用户信息放到vue 状态管理里面
                        console.log("-----以下是登录成功的用户信息-----");
                        console.log(resp.data.data);
                        localStorage.setItem("loginSuccessUserInfo.simoniu.com", JSON.stringify(resp.data.data));
                        setTimeout("javascript:window.location.href='/pIndex'", 2000);
                    } else {
                        //Message.error('用户名或者密码错误！');
                        this.$message.error('用户名或者密码错误！');
                    }
                }).catch(err => {
                    console.log(err);
                })
            },

            async doReg() {
                console.log('执行用户注册');
                let result = await this.checkIdentifyIsReg();
                console.log("result=" + result);
                if (result) {
                    //Message.error('该手机或者邮箱已经被注册！');
                    this.$message.error('该手机或者邮箱已经被注册！');
                    return;
                }
                //验证的验证码
                if (await this.checkValidateCode()) {
                    //验证码也验证成功。
                    //判断一下identify究竟是电子邮箱还是手机号码
                    if (graceChecker.check(this.regUser.identify, "email")) {
                        this.regUser.email = this.regUser.identify;
                        this.regUser.mobile = "";
                    } else if (graceChecker.check(this.regUser.identify, "phoneno")) {
                        this.regUser.mobile = this.regUser.identify;
                        this.regUser.email = "";
                    } else {
                        this.$message.error('注册信息格式非法！')
                        //Message.error('注册信息格式非法！')
                        return;
                    }

                    //以下是表单验证
                    if (this.regUser.password.length < 6) {
                        //Message.error('密码不能小于6位！');
                        this.$message.error('密码不能小于6位！');
                        return;
                    }
                    if (this.regUser.password != this.regUser.confirmpass) {
                        //Message.error('确认密码与密码不一致！');
                        this.$message.error('确认密码与密码不一致！');
                        return;
                    }
                    //执行用户注册
                    this.$store.dispatch("Reg", this.regUser).then(resp => {
                        this.$message.success('注册成功！')
                        //注册成功之后自动切换到登录的tab;
                        setTimeout(this.changeTab('userlogin'), 2000);
                    }).catch(err => {
                        console.log(err);
                    })
                }
            },
            changeRandomCodeImg() {
                console.log('执行更换验证码图片....');
            },
            //检查电子邮箱或者手机号码是否已经被注册
            async checkIdentifyIsReg() {
                let flag;
                await request.get('/commons/users/exist/identify', {
                    params: {
                        identify: this.regUser.identify
                    }
                }).then(resp => {
                    if (resp.data.code === 200) {
                        console.log("该账号是否已经被注册：" + resp.data.data);
                        //resp(resp.data.data);
                        flag = resp.data.data;
                    }
                }).catch(err => {
                    console.log(err);
                });
                return flag;
            },

            //给手机或者电子邮箱发送验证码
            sendMsgToMobileOrEmail() {
                let regUser ={
                    identify: this.regUser.identify,
                    token: this.token
                }
                this.$store.dispatch("SendMessageToMobileOrEmail",regUser).then(resp=>{
                    //console.log('发送成功，resp=>'+resp);
                    console.log(JSON.stringify(resp));
                    if (resp.data.code === 200) {
                        this.$message.success('验证码发送成功！');
                    }
                }).catch(err=>{
                    console.log(err);
                })
            },

            //检查验证码
            async checkValidateCode() {
                let flag;
                await request.get('/commons/msg/auth', {
                    params: {
                        token: this.token,
                        code: this.regUser.validateCode
                    }
                }).then(resp => {
                    if (resp.data.code === 400) {
                        //Message.error('验证码验证失败！');
                        this.$message.error('验证码验证失败！')
                        flag = false;
                    } else {
                        flag = true;
                    }
                }).catch(err => {
                    console.log(err);
                });
                return flag;
            }
        }
    }
</script>

<style scoped>
    .loginDiv {
        width: 100%;
        height: 520px;
        margin: 0px auto;
        background: lightblue;
        display: flex;
        justify-content: space-around;
    }

    #backlogo {
        margin: 40px 0 0 0px;
    }

    .loginForm {
        margin: 20px;
        background: #FFFFFF;
        width: 480px;
        border-radius: 0px;
    }

    .el-tabs {
        background: #FFFFFF;
    }

    .el-tab-pane {
        background: #FFFFFF;
    }

    .el-input {
        width: 280px;
    }
</style>